<?php
declare (strict_types = 1);

namespace app\common\listener\websocket;
use app\adminapi\model\Admin\Admin;
use adminmatrix\swoole\Websocket;
use think\Container;
use adminmatrix\swoole\websocket\Event;

class Message
{

    public $websocket = null;
    public function __construct(Container  $container){
        $this->websocket = $container->make(Websocket::class);
    }
    /**
     * 事件监听处理
     * @param Event $event
     */
    public function handle(  $frame)
    {
        echo "监听接听事件";
        $data = json_decode($frame->data , true);

        switch ($data['type'])
        {
            case 'chat':
                return $this->chat($data , $frame);
                break;
            case 'login':
                return $this->login($data , $frame);
            default:
                dump($frame);
        }
    }

    /**
     * 测试类型
     * @param Event $event $event
     */
    public function test(Event $event)
    {
        $msg = json_encode($event->data,256);
        $this->websocket->emit('callback', $msg);
    }

    private function chat( array $data , $frame)
    {
        // 方法1：通过frame对象直接获取fd
        $client_id = $frame->fd;
        echo "client_id = $client_id";
        // 方法2：通过Websocket类获取当前连接的fd
        $client_id = $this->websocket->getSender();

        echo "当前客户端ID：{$client_id}";

        echo "消息处理\\h";
        dump($data);
    }

    /**
     * 处理登录事件
     * @param array $data
     * @param $frame
     * @return void
     */
    private function login( array $data , $frame)
    {
        // 方法1：通过frame对象直接获取fd
        $fd_id = $frame->fd;
        // 方法2：通过Websocket类获取当前连接的fd
        $client_id = $this->websocket->getSender();
        $admin = Admin::where('id' , $data['userId'])->findOrEmpty();
        if ($admin->isEmpty())
            $this->websocket->emit(["type"=>'error']);
        echo "123";
        $this->websocket->emit("login" , ["message" => "登录成功" , 'type'=>'Notification']);
    }
}
